<template>
  <Modal v-model="modelIsOpen" width="650" mask :closable="false">
    <template #footer>
      <Button size="default" @click="cancel" :loading="btnLoading">取消</Button>
      <!-- <Poptip
        class="ml-10"
        placement="bottom-start"
        transfer
        :disabled="popDisabled"
      >
        <Button type="primary" size="default" :loading="btnLoading" @click="ok"
          >导出</Button
        >
        <template #content>
          <Progress :percent="downPercent" :status="downStatus" />
        </template>
      </Poptip> -->
      <Button type="primary" size="default" :loading="btnLoading" @click="ok"
        >导出</Button
      >
    </template>
    <Space direction="vertical" size="default" type="flex">
      <zz-Label text="导出"></zz-Label>

      <div class="select-emport-mode-box">
        <zz-Form ref="zzForm" title="请选择导出模式">
          <div class="select-emport-mode">
            <RadioGroup
              v-model="emportMode"
              size="small"
              @on-change="changeEmportMode"
            >
              <Radio label="cur">导出当前页</Radio>
              <Radio label="all">导出所有</Radio>
              <Radio label="setting">自定义导出</Radio>
            </RadioGroup>
          </div>
        </zz-Form>
      </div>

      <zz-Form
        ref="zzForm"
        title="自定义导出配置"
        :model="model"
        :rules="ruleValidate"
      >
        <Col span="12">
          <FormItem label="文件名称">
            <Input
              v-model="model.fileName"
              :disabled="emportMode !== 'setting'"
              :border="emportMode === 'setting'"
              clearable
              placeholder="请输入..."
            ></Input>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="文件格式">
            <Select
              v-model="model.format"
              clearable
              :disabled="emportMode !== 'setting'"
              v-if="emportMode === 'setting'"
            >
              <Option
                v-for="item in formatList"
                :value="item.value"
                :key="item.key"
              >
                {{ item.label }}
              </Option>
            </Select>
            <Input
              v-model="model.format"
              :disabled="emportMode !== 'setting'"
              :border="false"
              clearable
              placeholder="请输入..."
              v-if="emportMode !== 'setting'"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="是否打包">
            <RadioGroup v-model="model.isZip">
              <Radio label="0" :disabled="emportMode !== 'setting'">
                <span>否</span>
              </Radio>
              <Radio label="1" :disabled="emportMode !== 'setting'">
                <span>是</span>
              </Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col span="24">
          <FormItem label="表头设置">
            <zz-Transfer
              ref="transfer"
              :data="transferData"
              :list-style="{
                width: '220px',
                height: '290px',
                fontSize: '12px',
              }"
              @getTargetKeys="getTargetKeys"
              :titles="['表头备选', '表头已选']"
              :disabled="emportMode !== 'setting'"
              v-if="transferIsOpen"
            ></zz-Transfer>
          </FormItem>
        </Col>
      </zz-Form>
    </Space>
  </Modal>
</template>

<script>
import { saveAs } from 'file-saver'
export default {
  name: 'zzEmport',
  props: {
    titles: {
      type: Array,
      default: [],
    },
    fileds: {
      type: Array,
      default: [],
    },
    defaultFileName: {
      type: String,
      default: '',
    },
    tablePage: {
      type: Object,
      default: {},
    },
    urlObj: {
      type: Object,
    },
  },
  watch: {
    modelIsOpen: {
      async handler(newVal) {
        if (newVal) {
          // 渲染穿梭框组件
          this.transferIsOpen = true
          this.init()
        }
      },
      immediate: false,
    },
  },
  data() {
    return {
      modelIsOpen: false,
      transferIsOpen: false,
      btnLoading: false,
      emportMode: 'cur', // 导出模式
      model: {
        fileName: this.defaultFileName ? this.defaultFileName : '',
        format: '.xlsx',
        isZip: '0',
      },
      transferData: this.getMockData(),
      formatList: [],
      targetKeys: [],
      ruleValidate: {},
      downPercent: 0,
      downStatus: 'active',
      popDisabled: false,
    }
  },
  methods: {
    init() {
      this.formatList = [
        { key: 1, value: '.xlsx', label: 'xlsx' },
        { key: 2, value: '.xls', label: 'xls' },
      ]
    },
    changeEmportMode(val) {
      let transferFlag = val === 'setting' ? false : true
      this.transferData.forEach((e) => {
        e['disabled'] = transferFlag
      })
      this.$refs.transfer.allData.forEach((e) => {
        e['disabled'] = transferFlag
      })
    },
    getMockData() {
      let mockData = []
      for (let i = 1; i <= this.titles.length; i++) {
        mockData.push({
          key: i.toString(),
          label: this.titles[i - 1],
          disabled: true,
        })
      }
      return mockData
    },
    getTargetKeys(newTargetKeys) {
      this.targetKeys = newTargetKeys
    },
    async ok() {
      if (this.popDisabled) {
        this.popDisabled = false
      }
      this.btnLoading = true
      let params = {}
      if (this.emportMode === 'cur') {
        // 导出当前
        params = {
          fileName: this.defaultFileName,
          titleNames: this.titles,
          titles: this.fileds,
          chooseZip: false,
          queryParam: this.tablePage,
        }
      } else if (this.emportMode === 'all') {
        // 导出所有
        params = {
          fileName: this.defaultFileName,
          titleNames: this.titles,
          titles: this.fileds,
          chooseZip: false,
        }
      } else if (this.emportMode === 'setting') {
        if (this.targetKeys == null || this.targetKeys.length === 0) {
          this.$Message.warning('兄弟，表头设置了么？')
          this.btnLoading = false
          this.popDisabled = true
          return
        }

        // 自定义
        params = {
          fileName: this.model.fileName,
          titleNames: this.titles.filter((item, index) =>
            this.targetKeys.map((e) => Number(e) - 1).includes(index)
          ),
          titles: this.fileds.filter((item, index) =>
            this.targetKeys.map((e) => Number(e) - 1).includes(index)
          ),
          chooseZip: this.model.isZip === '1' ? true : false,
        }
        params.titleNames = this.sortByIndex(
          params.titleNames,
          this.targetKeys.map((e) => e - 1)
        )
        params.titles = this.sortByIndex(
          params.titles,
          this.targetKeys.map((e) => e - 1)
        )
      }

      // 进度条
      const downInterval = setInterval(() => {
        if (this.downPercent >= 90) {
          clearInterval(downInterval)
          return
        }
        this.downPercent += 10
      }, 500)

      try {
        const res = await this.urlObj.post(params)
        if (res) {
          let str = params.chooseZip ? '.zip' : this.model.format
          await this.openDownLoad(res, params.fileName + str)
          this.downPercent = 100
          this.btnLoading = false
          setTimeout(() => {
            this.cancel()
            clearInterval(downInterval)
          }, 1000)
        } else {
          this.downStatus = 'wrong'
          this.btnLoading = false
          this.$Message.error('呕吼，有点问题，获取文件失败了')
        }
      } catch (e) {
        this.downStatus = 'wrong'
        this.btnLoading = false
        this.$Message.error('呕吼，有点问题，获取文件失败了')
      }
    },
    cancel() {
      this.modelIsOpen = false
      this.reset()
    },
    reset() {
      this.model = {
        fileName: this.defaultFileName ? this.defaultFileName : '',
        format: '.xlsx',
        isZip: '0',
      }
      this.emportMode = 'cur'
      this.targetKeys = []
      this.transferData = this.getMockData()
      this.transferIsOpen = false
      this.$refs.transfer.reset()
    },
    async openDownLoad(ref, fileName) {
      if (ref) {
        let lists = ref
        var blob = new Blob([lists], { type: 'application/vnd.ms-excel' })
        // 方案一：file-saver
        await saveAs(blob, fileName)
        // 方案二：原生js
        // if ('download' in document.createElement('a')) {
        //   //非IE下载
        //   var downloadElement = document.createElement('a')
        //   var href = window.URL.createObjectURL(blob) //创建下载的链接
        //   downloadElement.href = href
        //   downloadElement.download = fileName //下载后文件名
        //   document.body.appendChild(downloadElement)
        //   downloadElement.click() //点击下载
        //   document.body.removeChild(downloadElement) //下载完成移除元素
        //   window.URL.revokeObjectURL(href) //释放掉blob对象
        // } else {
        //   //IE 10+ 下载
        //   navigator.msSaveBlob(blob, fileName)
        // }
      }
    },
    sortByIndex(arr, indexArr) {
      // 使用 map 方法生成一个新数组，并根据索引排序
      const sortedArr = indexArr.map((index) => arr[index])
      return sortedArr
    },
  },
}
</script>

<style lang="less" scoped>
.ivu-radio-wrapper {
  font-size: 12px;
}
.select-emport-mode-box .main-form-box {
  border: 0px solid #ebebf0;
}
.select-emport-mode {
  margin-left: 10px;
}
:deep(.ivu-transfer-list-header) {
  text-align: initial;
}
:deep(.ivu-transfer-list-content-item) {
  text-align: left;
}
:deep(.ivu-transfer-list-content-item > span) {
  font-size: 12px;
}
:deep(.ivu-transfer-operation) {
  width: 38px;
  margin-left: 22px;
}
</style>
